package com.ale.oxetool.service;

import org.apache.commons.net.telnet.TelnetClient;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * Created by guoshunw on 2016/5/19.
 */
public class TelnetOXEConnection extends OXEConnection {

    private TelnetClient telnet = new TelnetClient();
    public static String phonePrompt = "NoePhone >";

    private void init() throws IOException {
        telnet.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(5));
        telnet.setDefaultTimeout(0);
        connect(true);
    }

    /**
     * This constructor is used for NOE phone telnet connection
     * */
    TelnetOXEConnection(String host) throws IOException {
        super(host, "", "");
        setPort(23);
        init(false);
        readUntil(phonePrompt);
    }


    public TelnetOXEConnection(String host, String username, String password) throws IOException {
        super(host, username, password);
        setPort(23);
        init();
    }

    private void init(boolean autoLogin) throws IOException {
        telnet.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(5));
        telnet.setDefaultTimeout(0);
        connect(autoLogin);
    }


    TelnetOXEConnection(OXEServerSettings oxeServerSettings) throws IOException {
        super(oxeServerSettings);
        init();
    }

    @Override
    public boolean isSSHConnection() {
        return false;
    }

    @Override
    public boolean login(String username, String password) throws IOException {
        if (!username.isEmpty() && !password.isEmpty()) {
            readUntil("login:");
            writeText(username);
            readUntil("Password:");
            writeText(password);
        }
        boolean isCorrect = readUntil(prompt, "incorrect").contains(prompt);
        if(isCorrect){
            // disable timeout
            sendCommand(serverTimeoutDisabledCmd);
        }
        return isCorrect;
    }

    @Override
    public boolean connect(boolean autoLogin) throws IOException {
        telnet.connect(getHost(), getPort());
        telnet.setKeepAlive(true);

        bis = new BufferedInputStream(telnet.getInputStream());
        telnet.setKeepAlive(true);
        out = new PrintWriter(telnet.getOutputStream());
        return !autoLogin || login(getUsername(), getPassword());
    }

    @Override
    public void disconnect() {
        if (null == telnet) return;
        if (!telnet.isConnected()) return;
        try {
            writeText("exit");
            telnet.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public boolean isConnected() {
        return telnet.isConnected();
    }
}
